using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;

namespace ScrewTurn.Wiki {

	public partial class JsFileTree : System.Web.UI.UserControl {

		private string onclickCommand = "";
		private string hrefCommand = "GetFile.aspx?File=$";

		protected void Page_Load(object sender, EventArgs e) {
			RenderContent();
		}

		/// <summary>
		/// Renders the content of the control.
		/// </summary>
		public void RenderContent() {
			StringBuilder sb = new StringBuilder();
			sb.Append(@"<div id=""FileTreeDiv"">");

			InsertContent(Settings.UploadDirectory, sb);

			sb.Append("</div>");

			lblContent.Text = sb.ToString();
		}

		private void InsertContent(string path, StringBuilder sb) {
			string[] directories = Directory.GetDirectories(path);
			string[] files = Directory.GetFiles(path);

			for(int i = 0; i < directories.Length; i++) {
				sb.Append("<div>");
				sb.Append(@"<a href=""#"" class=""subdirlink"" onclick=""javascript:return __ToggleDiv('" + BuildID(directories[i]) + @"');"">");
				sb.Append(directories[i].Substring(directories[i].LastIndexOf("\\") + 1).Replace("\\", "/"));
				sb.Append("</a></div>");
				sb.Append(@"<div style=""display: none;"" class=""subtreediv"" id=""");
				sb.Append(BuildID(directories[i]));
				sb.Append(@""">");
				InsertContent(directories[i], sb);
				sb.Append("</div>");
			}

			for(int i = 0; i < files.Length; i++) {
				sb.Append(@"<div><a href=""");
				sb.Append(hrefCommand.Replace("$", Tools.UrlEncode(files[i].Substring(Settings.UploadDirectory.Length).Replace("\\", "/")).Replace("'", "\\'")));
				sb.Append(@""" onclick=""");
				sb.Append(onclickCommand.Replace("$", Tools.UrlEncode(files[i].Substring(Settings.UploadDirectory.Length).Replace("\\", "/")).Replace("'", "\\'")));
				sb.Append(@""" class=""filelink"">");
				sb.Append(Path.GetFileName(files[i]));
				sb.Append("</a></div>");
			}
		}

		private string BuildID(string input) {
			int hash = input.GetHashCode();
			if(hash < 0) hash *= -1;
			return "d" + hash.ToString();
		}

		/// <summary>
		/// Gets or sets the Href file Command.
		/// </summary>
		public string HrefCommand {
			get { return hrefCommand; }
			set { hrefCommand = value; }
		}

		/// <summary>
		/// Gets or sets the OnClick file Command.
		/// </summary>
		public string OnClickCommand {
			get { return onclickCommand; }
			set { onclickCommand = value; }
		}

	}

}
